<template>
  <view
    class="tabbar"
    v-if="showTabBar"
    :style="[globalStyle]"
  >
    <view class="tabbar-menu">
      <view
        class="tabbar-menu-item"
        v-for="(item, index) in tabbar"
        :key="index"
        :class="{ active: isActive(item.url), prominent: item.type === 'prominent' }"
        :data-to="item.url"
        @click="handelMenuClick(item.url)"
      >
        <view
          v-if="item.type === 'prominent'"
          class="iconfont tabbar-menu-item-prominent"
          :class="item.icon"
        ></view>
        <view
          class="iconfont tabbar-menu-item-icon"
          :class="item.type !== 'prominent' ? item.icon : ''"
        ></view>
        <text>{{ item.text }}</text>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    name: "TabBar",
    props: {
      showTabBar: {
        type: Boolean,
        default: true,
      },
    },
    data() {
      return {
        tabbar: [
          {
            icon: "icon-home",
            text: "首页",
            url: "/pages/index/index",
            type: "normal",
          },
          {
            icon: "icon-tutorial",
            text: "教程",
            url: "/pages/tutorial/index",
            type: "normal",
          },
          {
            icon: "icon-paint",
            text: "画板",
            url: "/pages/painter/index",
            type: "prominent",
          },
          {
            icon: "icon-demonstration",
            text: "画展",
            url: "/pages/show/index",
            type: "normal",
          },
          {
            icon: "icon-user-fill",
            text: "我的",
            url: "/pages/ucenter/index",
            type: "normal",
          },
        ],
      };
    },
    mounted() {
      uni.hideTabBar();
    },
    methods: {
      isActive(url) {
        //取得当前router
        const pages = getCurrentPages();
        const currentPage = pages[pages.length - 1];
        // currentPage.route pages/index/index
        // url /pages/index/index
        if (currentPage && currentPage.route) {
          console.log("currentPage.route", currentPage.route);
          // 如果url第一个字符是/，则去掉，否则相等
          return currentPage.route === url.replace(/^\//, "");
        }
        return false;
      },

      handelMenuClick(url) {
        uni.switchTab({
          url,
          success: function (res) {
            console.log("switchTab success", res);
          },
          fail: function (res) {
            console.log("switchTab fail", res);
          },
        });
      },
    },

    //监控返回键
    onBackPress() {
      console.log("aaaaaaaaaaaaaaaaaaaaaa");
      const pages = getCurrentPages();
      const currentPage = pages[pages.length - 1];
      if (currentPage.route === "/pages/index/index") {
        return false;
      }
      uni.navigateBack({
        delta: 1,
      });
      return true;
    },
  };
</script>

<style lang="scss" scoped></style>
